# encoding: utf-8
"""

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lei.chang on '11/04/2025'
    comment: 智能翻译业务逻辑
"""
import asyncio
import json
import os.path
import time
from docx import Document
from docx.shared import Cm
from docx.shared import Pt

from project.model.translation import OutputFormat, Translation
from project.middleware.llm_model import LlmModel, deepseek_model
from project.prompts import PROMPTS_FOLDER
from project.output.docx import DOCX_FOLDER
from project.output.conversations import CONVERSATIONS_FOLDER
from project.service import assemble_prompt, extract_json, write_conversation


class TranslationService:
    """
    """
    @staticmethod
    async def translate(text: str, output_format: str, include_vocabulary: bool):
        """ 翻译
        :param text: 要翻译的文本
        :param output_format: 输出格式 json(不含word文件)/word(含word文件)
        :param include_vocabulary: 是否要包含专业词汇列表
        :return:
        """
        prompt = assemble_prompt(f'{PROMPTS_FOLDER}/translation.md', content=text)
        start_time_ts = int(time.time())
        result = await LlmModel(deepseek_model).async_chat(prompt=prompt)
        print(result)
        end_time_ts = int(time.time())
        # 记录会话日志
        write_conversation('translation', message=text, reply=result, duration=end_time_ts-start_time_ts)

        result = extract_json(result)
        translation = Translation(**result)
        ret_data = dict()
        ret_data['translation'] = ' '.join([v.chinese for v in translation.bilingual])
        if include_vocabulary:
            ret_data['vocabulary'] = translation.vocabulary
        if output_format == OutputFormat.word.value:
            # 写入 word文件
            docx_file_name = TranslationService.export_docx(translation)
            ret_data['word_document_url'] = f'/docx/{docx_file_name}'

        return ret_data

    @staticmethod
    def export_docx(translation: Translation):
        """
        :return:
        """
        doc = Document()
        doc.add_heading('翻译结果', level=1)

        # 中英文对照表
        table = doc.add_table(rows=1, cols=2, style='Table Grid')
        table.autofit = False
        table.columns[0].width = Cm(8)
        table.columns[1].width = Cm(8)
        hdr = table.rows[0].cells
        hdr[0].text, hdr[1].text = 'English', 'Chinese'
        hdr[0].paragraphs[0].runs[0].bold = True
        hdr[0].paragraphs[0].runs[0].font.size = Pt(14)
        hdr[1].paragraphs[0].runs[0].bold = True
        hdr[1].paragraphs[0].runs[0].font.size = Pt(14)

        for row in translation.bilingual:
            cells = table.add_row().cells
            cells[0].text = row.english
            cells[0].paragraphs[0].runs[0].font.size = Pt(12)
            cells[1].text = row.chinese
            cells[1].paragraphs[0].runs[0].font.size = Pt(12)

        # 词汇列表
        doc.add_heading('词汇表', level=1)
        table = doc.add_table(rows=1, cols=3, style='Table Grid')
        table.autofit = False
        table.columns[0].width = Cm(4)
        table.columns[1].width = Cm(4)
        table.columns[2].width = Cm(8)
        hdr = table.rows[0].cells
        hdr[0].text, hdr[1].text, hdr[2].text = 'English', 'Chinese', 'Explanation'
        hdr[0].paragraphs[0].runs[0].bold = True
        hdr[0].paragraphs[0].runs[0].font.size = Pt(14)
        hdr[1].paragraphs[0].runs[0].bold = True
        hdr[1].paragraphs[0].runs[0].font.size = Pt(14)
        hdr[2].paragraphs[0].runs[0].bold = True
        hdr[2].paragraphs[0].runs[0].font.size = Pt(14)

        for row in translation.vocabulary:
            cells = table.add_row().cells
            cells[0].text = row.english
            cells[0].paragraphs[0].runs[0].font.size = Pt(12)
            cells[1].text = row.chinese
            cells[1].paragraphs[0].runs[0].font.size = Pt(12)
            cells[2].text = row.explanation
            cells[2].paragraphs[0].runs[0].font.size = Pt(12)

        # 保存
        file_name = f'translation_{int(time.time())}.docx'
        doc.save(f'{DOCX_FOLDER}/{file_name}')

        return file_name

    @staticmethod
    def get_conversations():
        """
        :return:
        """
        records = []
        translation_log = f'{CONVERSATIONS_FOLDER}/translation.log'
        if not os.path.exists(translation_log):
            return records
        with open(translation_log, 'r', encoding='utf-8') as f:
            for line in f:
                records.append(json.loads(line))

        return records


if __name__ == "__main__":
    """
    """
    text = 'adfegeageqegcvjvegaljlvae'
    asyncio.run(
        TranslationService.translate(text=text,
                                     output_format=OutputFormat.word.value,
                                     include_vocabulary=True)
    )
